import Vue from 'vue'
import VueRouter from 'vue-router'

import Layout from '@/views/layout'
import Login from '@/views/login'
import Dashboard from '@/views/dashboard'
import Article from '@/views/article'
import NoFind from '@/views/noFind'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    //一级路由
    {
      path: '/',
      component: Layout,
      redirect: '/dashboard',//默认重定向
      //二级路由
      children: [
        { path: 'dashboard', component: Dashboard },
        { path: 'article', component: Article }
      ]
    },
    { path: '/login', component: Login },
    { path: '*', component: NoFind }//404重定向
  ],

})

import store from '@/store'
// 路由守卫
router.beforeEach((to, from, next) => {
  // 登录页面直接放行
  if (to.path === '/login') {
    next()
  } else {
    const token = store.state.user.token
    // 判断是否有token
    if (token) {
      // 放行
      next()
    } else {
      // 跳转回登录页
      next('/login')
    }
  }
})

export default router